import { v4 as uuidv4 } from 'uuid'

/**
 * 判断值是否为假
 * @param {any} value
 */
export const isFalsy = (value: unknown) => (value === 0 ? false : !value)

/**
 * 判断值是否为空
 * @param {any} value
 */
export const isVoid = (value: unknown) => value === undefined || value === null || value === ''

/**
 * 清理对象
 * @param {any} object
 */
export const cleanObject = (object: Record<string, unknown>) => {
	if (!object) {
		return {}
	}
	const result = { ...object }
	Object.keys(object).forEach((key) => {
		const value = result[key]
		if (isFalsy(value)) {
			delete result[key]
		}
	})
	return result
}

/**
 * 生成UUID
 * @returns 生成的UUID
 */
export function generateUUID() {
	return uuidv4()
}

/**
 * 防抖
 * @param {*} func
 * @param {number} delay
 */
export const debounce = (func: (...args: any[]) => void, delay: number) => {
	let timeout: NodeJS.Timeout | null = null
	return (...args: any[]) => {
		if (timeout) clearTimeout(timeout)
		timeout = setTimeout(() => {
			func(...args)
			timeout = null
		}, delay)
	}
}

/**
 * 节流
 * @param {*} fn
 * @param {number} delay
 * @returns
 */
export function throttle(fn: (...args: any[]) => void, delay = 300) {
	let timer: NodeJS.Timeout | null = null
	return (...args: any[]) => {
		if (timer) {
			return
		}
		timer = setTimeout(() => {
			fn(...args)
			timer = null
		}, delay)
	}
}

/**
 * 深拷贝
 * @param {any} obj
 * @returns {any}
 */
export function deepClone(obj) {
	if (typeof obj !== 'object' || obj == null) return obj
	const result = obj instanceof Array ? [] : {}
	for (const key in obj) {
		if (Object.prototype.hasOwnProperty.call(obj, key)) {
			result[key] = deepClone(obj[key]) // 递归
		}
	}
	return result
}
